import { $ } from "koishi"

export const name = "bab-experiment"

export const inject = ["database"]

export function apply(ctx) {
  ctx.model.extend("dgck81lnn-bab-experiment", {
    id: "char",
    name: "string",
    nick: "string",
    ctime: { type: "timestamp", nullable: true },
    atime: "timestamp",
  })

  ctx.on("message", async session => {
    let m
    const M = () => m ??= session.bot.getGuildMember(session.guildId, session.userId)
    const now = new Date()
    ctx.database.upsert("dgck81lnn-bab-experiment", [{
      id: session.userId,
      name: session.event?.user?.name ?? (await M())?.user?.name,
      nick: session.event?.member?.nick ?? (await M())?.nick,
      atime: now,
    }]).catch(e => ctx.logger.error(e))
  })
  ctx.on("guild-member-added", async session => {
    let m
    const M = () => m ??= session.bot.getGuildMember(session.guildId, session.userId)
    const now = new Date()
    ctx.database.upsert("dgck81lnn-bab-experiment", [{
      id: session.userId,
      name: session.event?.user?.name ?? (await M())?.user?.name,
      nick: session.event?.member?.nick ?? (await M())?.nick,
      ctime: now,
      atime: now,
    }]).catch(e => ctx.logger.error(e))
  })
}
